﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WindowsLive;

public partial class site : System.Web.UI.MasterPage
{
	private string strLoginCookie = "Zi255";
	public bool m_isLoggedIn = false;
	public string LiveToken = null, UserName = null;
	public WindowsLiveLogin wll = new WindowsLiveLogin("000000004000DCB5", @"FFS_what_a_PITA-fhs347hifshahh3f8a77t&*87*&T&*8tFffa");
	public WindowsLiveLogin.User LiveUser;

	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			// Bind tree menu
			tvMenu.DataSource = smData;
			tvMenu.DataBind();
		}

		#region Init WLL
		HttpCookie loginCookie = Request.Cookies[strLoginCookie];
		string Action = Request["Action"];
		if (loginCookie != null)
		{
			string token = loginCookie.Value;
			if (!string.IsNullOrEmpty(token))
			{
				LiveUser = wll.ProcessToken(token);
				if (LiveUser != null) 
					LiveToken = LiveUser.Id;
			}
		}
		hfLiveToken.Value = LiveToken;

		#endregion Init WLL
		#region Do Windows Live Login request action

		switch (Action)
		{
			case "login":
				LiveUser = wll.ProcessLogin(Request.Form);
				loginCookie = new HttpCookie(strLoginCookie);
				if (LiveUser != null)
				{
					loginCookie.Value = LiveUser.Token;
					if (LiveUser.UsePersistentCookie) loginCookie.Expires = DateTime.Now.AddYears(10);
				}
				else loginCookie.Expires = DateTime.Now.AddYears(-10);
				Response.Cookies.Add(loginCookie);
				Response.Redirect("default.aspx");
				break;
			case "logout":
				loginCookie = new HttpCookie(strLoginCookie);
				loginCookie.Expires = DateTime.Now.AddYears(-10);
				Response.Cookies.Add(loginCookie);
				Response.Redirect("default.aspx");
				Response.End();
				break;
			case "clearcookie":
				loginCookie = new HttpCookie(strLoginCookie);
				loginCookie.Expires = DateTime.Now.AddYears(-10);
				Response.Cookies.Add(loginCookie);

				string type;
				byte[] content;
				wll.GetClearCookieResponse(out type, out content);
				Response.ContentType = type;
				Response.OutputStream.Write(content, 0, content.Length);
				break;
			default:
				break;
		}
		m_isLoggedIn = !string.IsNullOrEmpty(hfLiveToken.Value.Trim());
		#endregion


		lblLive.Text = m_isLoggedIn
			? "Log out"
			: "Log Into Windows Live";
	}


}